package com.ruoyi.other.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.check.CheckEmptyUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.other.domain.Region;
import com.ruoyi.other.mapper.RegionMapper;
import com.ruoyi.other.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 城市列表Controller
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@RestController
@RequestMapping("/region/region")
public class RegionController extends BaseController {
    @Autowired
    private IRegionService regionService;
    @Resource
    private RegionMapper regionMapper;

    /**
     * 查询城市列表列表
     */
    @PreAuthorize("@ss.hasPermi('region:region:list')")
    @GetMapping("/list")
    public TableDataInfo list(Region region) {
        startPage();
        List<Region> list = regionService.selectRegionList(region);
        return getDataTable(list);
    }

    /**
     * 导出城市列表列表
     */
    @PreAuthorize("@ss.hasPermi('region:region:export')")
    @Log(title = "城市列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Region region) {
        List<Region> list = regionService.selectRegionList(region);
        ExcelUtil<Region> util = new ExcelUtil<Region>(Region.class);
        util.exportExcel(response, list, "城市列表数据");
    }

    /**
     * 获取城市列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('region:region:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(regionService.selectRegionById(id));
    }

    /**
     * 新增城市列表
     */
    @PreAuthorize("@ss.hasPermi('region:region:add')")
    @Log(title = "城市列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Region region) {
        return toAjax(regionService.insertRegion(region));
    }

    /**
     * 修改城市列表
     */
    @PreAuthorize("@ss.hasPermi('region:region:edit')")
    @Log(title = "城市列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Region region) {
        return toAjax(regionService.updateRegion(region));
    }

    /**
     * 删除城市列表
     */
    @PreAuthorize("@ss.hasPermi('region:region:remove')")
    @Log(title = "城市列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(regionService.deleteRegionByIds(ids));
    }

    @GetMapping(value = "selectAllCity")
    public AjaxResult selectAllCity(@RequestParam(required = false) String cityName) {
        List<Region> regions;
        if (CheckEmptyUtil.isEmpty(cityName)){
            regions = regionMapper.selectAllCity();
        }else {
            regions = regionMapper.selectCityByPartnerName(cityName);
        }

        Map<Integer, Region> cityMap = new HashMap<>();
        List<Region> rootCities = new ArrayList<>();
        if (CheckEmptyUtil.isEmpty(regions)) {
            return success(Collections.emptyList());
        }
        // 第一步：将所有城市转换为AddCityFareCityVo对象，并放入Map中
        for (Region region : regions) {
            Region regionVo = new Region();
            regionVo.setId(region.getId());
            regionVo.setPid(region.getPid());
            regionVo.setName(region.getName());
            regionVo.setCreateTime(region.getCreateTime());
            regionVo.setChildren(new ArrayList<>());
            cityMap.put(regionVo.getId(), regionVo);
        }

        // 第二步：构建城市树结构
        for (Region cityConfig2 : regions) {
            if (cityConfig2.getLevel()<=2){
                Region cityVo = cityMap.get(cityConfig2.getId());
                if (cityConfig2.getPid() == 0) {
                    // 如果是顶级城市，则添加到根城市列表中
                    rootCities.add(cityVo);
                } else {
                    // 否则，添加到对应父城市的children列表中
                    Region parentCityVo = cityMap.get(cityConfig2.getPid());
                    if (parentCityVo != null) {
                        parentCityVo.getChildren().add(cityVo);
                    }
                }
            }

        }

        return success(rootCities);
    }


}
